import java.io.File;
import java.io.IOException;

public class TellstickInterface {

	private static File tdToolFile;
	private static int tellstickRepetitions;
	private static boolean tellstickLock = false;

	private static String className = "TellstickInterface: ";

	public static void turnOffDevice(int tellstickID, String deviceName) {
		turnDevice(tellstickID, false, deviceName);
	}

	public static void turnOnDevice(int tellstickID, String deviceName) {
		turnDevice(tellstickID, true, deviceName);
	}

	public static void turnOffDevice(Device tellstickDevice) {
		turnDevice(tellstickDevice.getDeviceID(), false,
				tellstickDevice.getDeviceName());
	}

	public static void turnOnDevice(Device tellstickDevice) {
		turnDevice(tellstickDevice.getDeviceID(), true,
				tellstickDevice.getDeviceName());
	}

	public static void turnDevice(int tellstickID, boolean on, String deviceName) {
		DEBUG("turnDevice: " + deviceName + " " + tellstickID + " On: " + on
				+ " tellstickRepetitions: " + tellstickRepetitions);

		for (int i = 0; i < tellstickRepetitions; i++) {
			if (!tellstickLock) {
				tellstickLock = true;

				Runtime r = Runtime.getRuntime();
				String commandString = tdToolFile.getPath();
				commandString += on ? " -n " : " -f ";
				commandString += tellstickID;

				try {
					Process p = r.exec(commandString);
					p.waitFor();
				} catch (IOException ioe) {
					ioe.printStackTrace();
				} catch (InterruptedException ie) {
					ie.printStackTrace();
				}

				/*
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					
					e.printStackTrace();
				}
				*/
				
				tellstickLock = false;
			}
		}
	}

	public static void setTdToolFile(String tdToolFilePath) {
		DEBUG("setTdToolFile " + tdToolFilePath);

		tdToolFile = new File(tdToolFilePath);

		if (!tdToolFile.exists()) {
			tdToolFile = new File("");
		}
	}

	public static void setTellstickRepetitions(int tellstickRepetitions_) {
		if (tellstickRepetitions_ > 0) {
			tellstickRepetitions = tellstickRepetitions_;
		} else {
			tellstickRepetitions = 1;
		}
	}

	public static void init(String tdToolFilePath, int tellstickRepetitions_) {
		setTdToolFile(tdToolFilePath);
		setTellstickRepetitions(tellstickRepetitions_);
	}

	private static void DEBUG(String debugString) {
		Macros.DEBUG(className + debugString);
	}
}
